#pragma once
#include "Socket.hpp"
#include "Log.hpp"
#include <poll.h>
using namespace MyLogModule;
using namespace MySocketModule;

#define NUM (sizeof(fd_set) * 8)
const int gdefaultfd = -1;
#define ARRAY_SIZE 64
class PollServer
{
private:
    std::unique_ptr<Socket> _listen_socket;
    int16_t _port;
    bool _isrunning;
    struct pollfd* _fd_array;

// struct pollfd {
//     int   fd;         /* file descriptor */
//     short events;     /* requested events */
//     short revents;    /* returned events */
// };

public:
    PollServer(int16_t port)
        : _port(port), _listen_socket(make_unique<TcpSocket>())
        ,_fd_array(new pollfd[ARRAY_SIZE])
    {
        // _fd_array = new struct pollfd[ARRAY_SIZE];
    }

    ~PollServer()
    {
    }

    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        // 初始化辅助数组
        for (int i = 0; i < ARRAY_SIZE; i++)
        {
            _fd_array[i].fd = gdefaultfd;
            _fd_array[i].events = 0;
            _fd_array[i].revents = 0;
        }
        // 将listen_socket添加至辅助数组
        _fd_array[0].fd = _listen_socket->GetSockfd();
        _fd_array[0].events |= POLLIN;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            int timeout = 1000;
            int n = poll(_fd_array, ARRAY_SIZE, timeout);
            switch (n)
            {
            case 0:
                cout << "time out," << endl;
                break;
            case -1:
                cout << "select error" << endl;
                break;
            default:
                // rfds: 内核告诉用户，你关心的rfds中的fd，有哪些已经就绪了！！
                cout << "有事件就绪了..." << endl;
                Dispatcher();
                TestFd();
                break;
            }
        }
        _isrunning = false;
    }

    void Accepter()
    {
        InetAddr client;
        // 此时accept就不会阻塞了
        int newfd = _listen_socket->AcceptOrDie(&client);
        if (newfd < 0)
            return;
        else
        {
            cout << "get a new link,fd:" << newfd << endl;
            int pos = -1;
            for (int j = 0; j < ARRAY_SIZE; j++)
            {
                if (_fd_array[j].fd == gdefaultfd)
                {
                    pos = j;
                    break;
                }
            }
            if (pos == -1)
            {
                //可扩容
                cout << "服务器满载了..." << endl;
                close(newfd); // 关闭新连接
            }
            else
            {
                _fd_array[pos].fd = newfd; // 关心是否可读
                _fd_array[pos].events |= POLLIN;
            }
        }
    }

    void Recver(int who)
    {
        char buf[1024];
        size_t n = recv(_fd_array[who].fd, buf, sizeof(buf) - 1, 0);
        if (n > 0)
        {
            buf[n] = 0;
            cout << "Client# " << buf << endl;
            string str = "Echo#";
            str += buf;
            send(_fd_array[who].fd, str.c_str(), str.size(), 0); // bug
        }
        else if (n == 0)
        {
            LOG(LogGrade::DEBUG) << "客户端退出了,fd:" << _fd_array[who].fd;
            close(_fd_array[who].fd);
            _fd_array[who].fd = gdefaultfd;
            _fd_array[who].events = _fd_array[who].revents = 0;
        }
        else
        {
            LOG(LogGrade::DEBUG) << "客户端读取出错了,fd:" << _fd_array[who].fd;
            close(_fd_array[who].fd);
            _fd_array[who].fd = gdefaultfd;
            _fd_array[who].events = _fd_array[who].revents = 0;

        }
    }

    void Dispatcher()
    {
        for (int i = 0; i < ARRAY_SIZE; i++)
        {
            if (_fd_array[i].fd == gdefaultfd)
                continue;

            // 判断是否是listen_socket
            if (_fd_array[i].fd == _listen_socket->GetSockfd())
            {
                // 判断listen_socket是否在rfds中
                if (_fd_array[i].revents & POLLIN)
                {
                    Accepter();
                }
            }
            else
            {
                // 普通fd就绪了
                // 可以读了，不用阻塞！
                if (_fd_array[i].revents & POLLIN)
                {
                    Recver(i);  //进行IO
                }
            }
        }
    }

    void TestFd()
    {
        std::cout << "pollfd: ";
        for(int i = 0; i < ARRAY_SIZE; i++)
        {
            if(_fd_array[i].fd == gdefaultfd)
                continue;
            std::cout << _fd_array[i].fd << "[" << Events2Str(_fd_array[i].events)  << "] ";
        }
        std::cout << "\n";
    }
    std::string Events2Str(short events)
    {
        std::string s = ((events & POLLIN) ? "EPOLLIN" : "");
        s += ((events & POLLOUT) ? "POLLOUT" : "");
        return s;
    }

};